package com.tot.httpclient;


import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @see
 * <link>http://blog.csdn.net/authorzhh/article/details/7823957/<link/>
 * <link>http://ahopedog.iteye.com/blog/1154378<link/>
 * httpclientcomponents官方教程
 * <>http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html</>
 * Created by TOT on 2015/12/21.
 * 发送http请求主要包含以下步奏
 * 1，创建请求，更具http协议一共有八种请求。常见的油GET、POST、PUT等
 *      说明：http请求主要包含了URL,请求参数（param）,消息标头（head）.cookie放在head中
 * 2，创建HttpClient不同的client有不同的特性，一般使用ColsableHttpClient
 * 3，使用httpClient发送请求
 * 4,处理结果，HttpResponse封装了请求的结果，无论成功与否。请求信息都封装在该对象中。entity是返回的响应体，可以使用EntityUtils将其转
 * 换成字符串
 *
 */

public class HttpUtils {

    public static final String METHOD_NAME_POST = "POST";
    public static final String METHOD_NAME_PUT = "PUT";
    public static final String METHOD_NAME_GET = "GET";


    public String post(String url,ParamTable paramTable ,HeaderTable headerTable){
        HttpResponse httpResponse = send(METHOD_NAME_POST,url,paramTable,headerTable);
        if(httpResponse.getStatusLine().getStatusCode() == 200){
            try {
                return EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //记录异常
        return "";

    }
    public String get(String url,ParamTable paramTable ,HeaderTable headerTable){
        HttpResponse httpResponse = send(METHOD_NAME_GET,url,paramTable,headerTable);
        if(httpResponse.getStatusLine().getStatusCode() == 200){
            try {
                return EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //记录异常
        return "";
    }


    public static HttpResponse send(String method,String url,ParamTable paramTable,HeaderTable headerTable){
        try{
            //创建http请求。
            HttpRequestBase httpRequestBase = createHttpRequest(method, url, paramTable, headerTable);
            //创建请求客服端
            HttpClient client = createClient();
            return client.execute(httpRequestBase);

        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 创建http请求
     * @param method
     * @param url
     * @param paramTable
     * @param headerTable
     * @return
     * @throws Exception
     */
    public static HttpRequestBase createHttpRequest(String method,String url,ParamTable paramTable,HeaderTable headerTable) throws Exception {
        switch (method){
            case METHOD_NAME_GET:return createHttpGet(url, paramTable, headerTable);
            case METHOD_NAME_POST:return createHttpPost(url,paramTable,headerTable);
        }
        throw new Exception("invalid method exception:"+method);
    }
    public static HttpClient createClient(){
        return HttpClients.createDefault();
    }

    /**
     * 创建 get http请求
     * @param url
     * @param paramTable
     * @param headerTable
     * @return
     */
    private static HttpGet createHttpGet(String url,ParamTable paramTable,HeaderTable headerTable) throws Exception {
        if(isBlank(url)){
            throw new Exception("url is blank");
        }
        HttpGet get = new HttpGet();
        //设置heaer
        if(headerTable != null){
            Header[] headers = new Header[]{};
            get.setHeaders(headerTable.getHeaders().toArray(headers));
        }

        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            //设置参数
            if(paramTable != null){
                uriBuilder.addParameters(paramTable.getValuePairs());
            }
            get.setURI(uriBuilder.build());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return get;
    }

    /**
     * 创建post http请求
     * @param url
     * @param paramTable
     * @param headerTable
     * @return
     * @throws Exception
     */
    private static HttpPost createHttpPost(String url,ParamTable paramTable,HeaderTable headerTable) throws Exception {
        if(isBlank(url)){
            throw new Exception("url is blank");
        }
        HttpPost post = new HttpPost(url);
        if(paramTable != null){
            //添加参数
            HttpEntity httpEntity = new UrlEncodedFormEntity(paramTable.getValuePairs(), Charset.forName("UTF-8"));
            post.setEntity(httpEntity);
        }
        if(headerTable != null){
            //设置标题头信息

            Header[] headers = new Header[]{};
            post.setHeaders(headerTable.getHeaders().toArray(headers));
        }
        return post;
    }

    /**
     * 参数表
     */
    static class  ParamTable{
        private List<NameValuePair> valuePairs ;
        public ParamTable(){
            valuePairs = new ArrayList<>();
        }

        private NameValuePair createParamPair(String name,String value){
            if(isBlank(name)){
                return null;
            }
            return new BasicNameValuePair(name,value);
        }

        public void put(String name,String value){

            valuePairs.add(createParamPair(name,value));
        }

        public void createParamPairs(Map<String,String> params){
            if(params == null){return;}
            for(Map.Entry<String,String> entry:params.entrySet()){
                put(entry.getKey(), entry.getValue());
            }
        }
        public List<NameValuePair> getValuePairs(){
            return valuePairs;
        }
    }

    /**
     * 消息头表
     */
    static class HeaderTable{
        private static final String HEAD_COOKIE_NAME = "Cookie";
        private List<Header> headers;
        public HeaderTable(){
            headers = new ArrayList<>();
        }

        private Header createHead(String name,String value){
            if(isBlank(name)){
                return null;
            }
            return new BasicHeader(name,value);
        }
        private void put(String name,String value){
            headers.add(createHead(name,value));
        }
        public void createParamPairs(Map<String,String> params){
            if(params == null){return;}
            for(Map.Entry<String,String> entry:params.entrySet()){
                put(entry.getKey(), entry.getValue());
            }
        }
        public void addCookie(String name,String value){
            if(isBlank(name)||isBlank(value)){
                return;
            }
            put(HEAD_COOKIE_NAME,name+"="+value);
        }

        public void addCookie(String cookie){
            if(isBlank(cookie)){
                return;
            }
            put(HEAD_COOKIE_NAME,cookie);

        }

        public List<Header> getHeaders(){
            return headers;
        }
    }
    static boolean isBlank(String string){
        if(string == null ||string.length() ==0 ){
            return true;
        }
        return false;
    }


    public static void main(String[] args) throws Exception {
//        ParamTable paramTable = new ParamTable();
//        //c12092f2-f892-4b35-8885-92a2a9e87b0e
//        paramTable.put("loginName", "getgjx");
//        paramTable.put("loginPwd", "000000");
//        paramTable.put("isRememberMe", "false");
//        paramTable.put("isAdmin", "false");
//        paramTable.put("isPeremptory", "true");
////        HttpResponse response = send("POST","http://dev2.tmc.slyi.cc/tmcs/operator/operatorLogin.json",paramTable,null);
//        HeaderTable headerTable = new HeaderTable();
//        headerTable.addCookie("JSESSIONID=c12092f2-f892-4b35-8885-92a2a9e87b0e");
//        HttpResponse response = send("POST","http://dev2.tmc.slyi.cc/tmcs/tmc/showTmcBrandInfo.json",null,headerTable);
//        System.out.println(Arrays.toString(response.getAllHeaders()));
//        String resp = EntityUtils.toString(response.getEntity());
//        System.out.println(resp);
//

        String jsonParm = "{\n" +
                "  \"mobile\": 13689697290,\n" +
                "  \"verificationCode\": \"devTest\",\n" +
                "  \"passengers\": [\n" +
                "    {\n" +
                "      \"name\": \"小喜喜\",\n" +
                "      \"certificateType\": \"IDENTIFY_CARD\",\n" +
                "      \"certificateTypeDesc\": \"身份证\",\n" +
                "      \"certificateNumber\": \"511303199109205112\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"name\": \"小哈哈\",\n" +
                "      \"certificateType\": \"IDENTIFY_CARD\",\n" +
                "      \"certificateTypeDesc\": \"身份证\",\n" +
                "      \"certificateNumber\": \"511303199109205112\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"aboardPosition\": {\n" +
                "    \"cityArea\": {\n" +
                "      \"name\": \"高新区\"\n" +
                "    },\n" +
                "    \"positionDesc\": \"高新区详细地址\"\n" +
                "  },\n" +
                "  \"arrPosition\": {\n" +
                "    \"cityArea\": {\n" +
                "      \"name\": \"双流区\"\n" +
                "    },\n" +
                "    \"positionDesc\": \"双流国际机场\"\n" +
                "  },\n" +
                "  \"flightNumber\": \"CT0008\",\n" +
                "  \"flightDepTime\": \"2016-08-08 05:00:00\",\n" +
                "  \"voucherCode\": 1990\n" +
                "}";

        HttpEntity entity = new StringEntity(jsonParm,"UTF-8");
        HttpPost post = new HttpPost("http://localhost:8080/pa/order/");
        post.setHeader("Content-Type","application/json");
        post.setHeader("Accept","application/json");
        post.setHeader("Cache-Control","no-cache");
        post.setHeader("charset","UTF-8");
        post.setEntity(entity);
        HttpClient client = HttpClients.createDefault();
        org.apache.http.HttpResponse httpResponse = client.execute(post);
        String resStr = EntityUtils.toString(httpResponse.getEntity());
        System.out.println(resStr);



    }

}
